/**
 * 
 */
package cn.springsoter.core.tool.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.util.Map;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Maps;


/**
 * @author kevin
 *
 */
public class KeyStoreUtil {

	/**
	 * 缓存
	 */
	private static final Map<String, String> keyMap = Maps.newConcurrentMap();
	/**
	 * keystore存储的类型
	 */
	private static final String KEYSTORE_TYPE = "PKCS12";
	/**
	 * 存储算法
	 */
	private static final String SK_ALGORITHM = "PBE";
	
	/**
	 * 从文件里读取key
	 * 
	 * @param cacheKey	缓存key
	 * @param filePath	key的文件路径
	 * @return
	 */
	public static String getKeyFromFile(String cacheKey, String filePath){
        String key = keyMap.get(cacheKey);
        if(StringUtils.isBlank(key)){
            key = FileUtil.readPEMFile(filePath);
            keyMap.put(cacheKey, key);
        }
        return key;
    }
	
	/**
	 * 从resources目录下读取key
	 * 
	 * @param cacheKey	缓存key
	 * @param stream	文件流
	 * @return
	 */
	public static String getKeyFromResources(String cacheKey, String filePath){
		String key = keyMap.get(cacheKey);
		if(StringUtils.isBlank(key)){
			key = FileUtil.readResourcesFile(filePath);
			keyMap.put(cacheKey, key);
		}
		return key;
	}
	
	/**
	 * 从字符串中读取key
	 * 
	 * @param cacheKey	缓存key
	 * @param keyStr	key字符串，开头和结束不能包含“-----BEGIN PRIVATE KEY-----” 和 “-----END PRIVATE KEY-----” 需要删掉这2行
	 * @return
	 */
	public static String getKeyFromString(String cacheKey, String keyStr){
        String key = keyMap.get(cacheKey);
        if(StringUtils.isBlank(key)){
            key = keyStr;
            keyMap.put(cacheKey, key);
        }
        return key;
    }
	
	/**
     * 保存密钥到keystore
     * 
     * @param alias		key的名称
     * @param content	内容
     * @param keyStoreLocation	存储位置，默认在classpath/keystore/
     * @param keyStorePassword	存储密码
     * @throws Exception
     */
    public static void storeKey(String alias, String content, String keyStoreLocation, String keyStorePassword)
            throws Exception {
    	
        SecretKeyFactory factory = SecretKeyFactory.getInstance(SK_ALGORITHM);
        //存储值
        SecretKey generatedSecret = factory.generateSecret(new PBEKeySpec(content.toCharArray()));

        KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
        ks.load(null, keyStorePassword.toCharArray());
        KeyStore.PasswordProtection keyStorePP = new KeyStore.PasswordProtection(keyStorePassword.toCharArray());

        ks.setEntry(alias, new KeyStore.SecretKeyEntry(generatedSecret), keyStorePP);

        FileOutputStream out = new java.io.FileOutputStream(FileUtil.touch(keyStoreLocation));
        ks.store(out, keyStorePassword.toCharArray());
    }
    
    /**
     * 从keystore取出密钥
     * 
     * @param alias		key的名称
     * @param keystoreLocation	存储位置，默认在classpath/keystore/
     * @param keyStorePassword	存储密码
     * @return
     * @throws Exception
     */
    public static String getStoreKey(String alias, String keystoreLocation, String keyStorePassword) throws Exception{
    	
        KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
        ks.load(null, keyStorePassword.toCharArray());
        KeyStore.PasswordProtection keyStorePP = new KeyStore.PasswordProtection(keyStorePassword.toCharArray());

        FileInputStream in = new FileInputStream(new File(keystoreLocation));

        ks.load(in, keyStorePassword.toCharArray());

        SecretKeyFactory factory = SecretKeyFactory.getInstance(SK_ALGORITHM);

        KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry)ks.getEntry(alias, keyStorePP);

        PBEKeySpec keySpec = (PBEKeySpec)factory.getKeySpec(ske.getSecretKey(), PBEKeySpec.class);

        char[] content = keySpec.getPassword();

        return new String(content);

    }
}
